//
//  LandingViewController.m
//  Light
//
//  Created by 骁唐 on 15/9/7.
//  Copyright (c) 2015年 骁唐. All rights reserved.
//

#import "LandingViewController.h"
#import "AFNetworking.h"
#import "NetworkTool.h"
#import "TestingViewController.h"
#import "UserConfig.h"

#import "UMSocialSnsPlatformManager.h"
#import "UMSocialAccountManager.h"
#import "NameViewController.h"
#import "HomeTwoViewController.h"
#import "SliderViewController.h"
#import "constantDefinition.h"
#import "MBProgressHUD.h"
#import "ProtocolViewController.h"

@interface LandingViewController ()<UIGestureRecognizerDelegate,UITextFieldDelegate,MBProgressHUDDelegate>
@property (weak, nonatomic) IBOutlet UITextField *phoneText;
@property (weak, nonatomic) IBOutlet UITextField *passwordText;
@property (weak, nonatomic) IBOutlet UIImageView *backGround;
//协议选中按钮
@property (weak, nonatomic) IBOutlet UIButton * buttonSelect;

@property (weak, nonatomic) MBProgressHUD *mbProgressHud;

@end

@implementation LandingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    
    self.phoneText.keyboardType = UIKeyboardTypeNumberPad;
    self.phoneText.delegate = self;
    self.passwordText.delegate = self;
    self.passwordText.returnKeyType = UIReturnKeyDone;

    [self.passwordText resignFirstResponder];
    
    MBProgressHUD *progressView = [[MBProgressHUD alloc]initWithView:self.view];
    progressView.delegate       = self;
    progressView.labelText      = @"";
    self.mbProgressHud       = progressView;
    [self.view addSubview:progressView];
    [_mbProgressHud show:YES];
    self.mbProgressHud.hidden = YES;

}

#pragma mark-
#pragma mark 点击空白处，键盘回收
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.phoneText resignFirstResponder];
    [self.passwordText resignFirstResponder];
}
#pragma mark-
#pragma mark 键盘return按钮处理优化
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];//隐藏键盘
    if (textField == self.passwordText)
    {//密码   OK按钮就应该直接调起注册
        if (!self.buttonSelect.selected)
        {
            TJJALERT_VIEW(@"请阅读并同意用户注册协议");
        }
        else
        {
            [self loadRegist];//调起注册
        }
    }
    return YES;
}
#pragma mark-
#pragma mark 限制手机号码11位输入
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.phoneText)
    {//手机限制11位输入
        if (range.location==11)
        {
            //            [self.phoneTF resignFirstResponder];
            textField.text=[textField.text substringToIndex:10];
            return YES;
        }
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return  YES;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return [gestureRecognizer isKindOfClass:UIScreenEdgePanGestureRecognizer.class];
}

- (IBAction)logon {
    if (!self.buttonSelect.selected)
    {
        TJJALERT_VIEW(@"请阅读并同意用户注册协议");
    }
    else
    {
        [self loadRegist];//调起注册
    }
}

#pragma mark -
#pragma mark 按钮点击
- (IBAction)buttonClick:(UIButton *)button
{
    switch (button.tag)
    {
        case 328:
        {//按钮选中
            button.selected = !button.selected;
        }
            break;
        case 329:
        {//跳转至用户协议
            //切换storyboard
            UIStoryboard *connect = [UIStoryboard storyboardWithName:@"User" bundle:nil];
            ProtocolViewController *vc = [connect instantiateViewControllerWithIdentifier:@"protocolId"];//根据id设置
            vc.mark = @"landing";//标记从设置进入的连接设备操作
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        default:
            break;
    }
}

#pragma mark -
#pragma mark 注册网络请求
- (void)loadRegist
{
    [self.view endEditing:YES];
    //[self performSegueWithIdentifier:@"landingToTesting" sender:nil];
    if ([TJJDefines isMobile:self.phoneText.text])
    {//手机格式正确，需要判断密码长度是否为0
        if (self.passwordText.text.length > 0)
        {
            NSDictionary *dic= @{@"cellPhone":self.phoneText.text};
            //__weak LandingViewController *weakSelf = self;
            AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
            httpManager.requestSerializer = [[AFHTTPRequestSerializer alloc]init];
            httpManager.responseSerializer = [[AFHTTPResponseSerializer alloc]init];
            //地址
            [httpManager POST:CHECK_PHONE parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSDictionary *retDic = [NetworkTool toNSDictionary:responseObject];
                if ([retDic[@"flag"] intValue] == 1) {
                    [self performSegueWithIdentifier:@"landingToTesting" sender:nil];
                }else if([retDic[@"flag"] intValue] == -1)
                {
                    TJJALERT_VIEW(@"此手机号已被注册，请直接登录或找回密码");
                }
            }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@" ");
            }];
        }
        else
        {
            TJJALERT_VIEW(@"密码不能设置为空！");
        }
    }
    else
    {
        TJJALERT_VIEW(ERROR_MOBILEINFO);
    }
}
//   #pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
#pragma mark -
#pragma mark 页面传值
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"landingToTesting"]) {
        TestingViewController *__weak testing = [segue destinationViewController];
        testing.password = self.passwordText.text;
        testing.phoneText = self.phoneText.text;
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //强制竖屏
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:
                                        UIInterfaceOrientationPortrait]  forKey:@"orientation"];
    //SXW__标记，设置背景
    long long int currentTimeInt = [TJJDefines getTimeIntSince1970Current];
    if (currentTimeInt>=16200&& currentTimeInt <=34200) {
        self.backGround.image = [UIImage imageNamed:@"backgroundOne"];
    }else if (currentTimeInt>34200 && currentTimeInt<=55800)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundTwo"];
    }else if (currentTimeInt>55800 && currentTimeInt<=70200)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundThree"];
    }else if(currentTimeInt >70200 || currentTimeInt<16200)
    {
        self.backGround.image = [UIImage imageNamed:@"background_night"];
    }
}


- (IBAction)weixinClick {
    [self.view endEditing:YES];//键盘回收
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToWechatSession];
    
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        
        if (response.responseCode == UMSResponseCodeSuccess) {
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary]valueForKey:UMShareToWechatSession];
            NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
            NSDictionary *dic= @{@"uid":snsAccount.usid};
            AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
            httpManager.requestSerializer = [[AFHTTPRequestSerializer alloc] init];
            httpManager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
            //地址
            [httpManager POST:URL_REGIST_ANOTHER parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
                UserConfig *config = [UserConfig sharingUserConfig];
                NSDictionary *retDic = [NetworkTool toNSDictionary:responseObject];
//                __weak LandingViewController *weakSelf = self;
                if ([retDic[@"a"] intValue] == 1)
                {
                    [config setToken:retDic[@"b"]];
                    if ([retDic[@"c"] intValue] == 1)
                    {
                        
                        BOOL HaveRoot = NO;//标记是否有Root
                        for (UIViewController * controller in self.navigationController.viewControllers)
                        {
                            if ([controller isKindOfClass:[SliderViewController class]])
                            {//如果是rootView
                                HaveRoot = YES;
                                [self.navigationController popToViewController:controller animated:YES];
                            }
                        }
                        if (!HaveRoot)
                        {
                            HomeTwoViewController *homet = [[HomeTwoViewController alloc] init];
                            SliderViewController *slider = [SliderViewController sharedSliderController];
                            [config setHaveLogin:@"login"];
                            if (SCREEN_WIDTH > 320)
                            {
                                slider.LeftSContentOffset =  SCREEN_WIDTH-WIDTH_MAIN_6*SCREEN_SCALE;//SXW__设置侧边栏
                            }
                            else
                            {
                                slider.LeftSContentOffset =  SCREEN_WIDTH-WIDTH_MAIN*SCREEN_SCALE;//SXW__设置侧边栏
                            }                            slider.LeftSContentScale = 1;//左视图缩小，1表示不缩小。
                            
                            UIStoryboard *userSt = [UIStoryboard storyboardWithName:@"User" bundle:nil];
                            slider.LeftVC = [userSt instantiateViewControllerWithIdentifier:@"userViewId"];
                            
                            slider.MainVC = homet;
                            AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
                            UINavigationController *navigationVc = [[UINavigationController alloc]initWithRootViewController:slider];
                            navigationVc.navigationBar.hidden = YES;
                            delegate.window.rootViewController = navigationVc;
                        }
                        //    [self.navigationController pushViewController:slider animated:YES];
//                            [weakSelf.navigationController pushViewController:slider animated:YES];
    
                    }else if ([retDic[@"c"] intValue] == 0)
                    {
                        [self performSegueWithIdentifier:@"landingToName" sender:nil];
                    }
                
                }else if ([retDic[@"a"] intValue] == 0) {
                    NSLog(@"00000000000");
                    
                }else if([retDic[@"a"] intValue] == -1){
                    NSLog(@"-11111111");
                    
                }
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"shibai ");
                _mbProgressHud.hidden = YES;
            }];
            
        }
        
    });
    
}
- (IBAction)weiboClick:(UIButton *)sender {
    [self.view endEditing:YES];//键盘回收
    self.mbProgressHud.hidden = NO;
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
    UserConfig *config = [UserConfig sharingUserConfig];
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        
        //          获取微博用户名、uid、token等
        
        if (response.responseCode == UMSResponseCodeSuccess) {
            
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToSina];
            
            NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
            //传的参数
            NSDictionary *dic= @{@"uid":snsAccount.usid};
            AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
            httpManager.requestSerializer = [[AFHTTPRequestSerializer alloc] init];
            httpManager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
            //地址
            [httpManager POST:URL_REGIST_ANOTHER parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
                
                NSDictionary *retDic = [NetworkTool toNSDictionary:responseObject];
//                __weak LandingViewController *weakSelf = self;
                if ([retDic[@"a"] intValue] == 1)
                {
                    [config setToken:retDic[@"b"]];
                    if ([retDic[@"c"] intValue] == 1)
                    {
                        BOOL HaveRoot = NO;//标记是否有Root
                        for (UIViewController * controller in self.navigationController.viewControllers)
                        {
                            if ([controller isKindOfClass:[SliderViewController class]])
                            {//如果是rootView
                                HaveRoot = YES;
                                [self.navigationController popToViewController:controller animated:YES];
                            }
                        }
                        if (!HaveRoot)
                        {
                            HomeTwoViewController *homet = [[HomeTwoViewController alloc] init];
                            SliderViewController *slider = [SliderViewController sharedSliderController];
                            [config setHaveLogin:@"login"];
                            if (SCREEN_WIDTH > 320)
                            {
                                slider.LeftSContentOffset =  SCREEN_WIDTH-WIDTH_MAIN_6*SCREEN_SCALE;//SXW__设置侧边栏
                            }
                            else
                            {
                                slider.LeftSContentOffset =  SCREEN_WIDTH-WIDTH_MAIN*SCREEN_SCALE;//SXW__设置侧边栏
                            }
                            slider.LeftSContentScale = 1;//左视图缩小，1表示不缩小。
                            UIStoryboard *userSt = [UIStoryboard storyboardWithName:@"User" bundle:nil];
                            slider.LeftVC = [userSt instantiateViewControllerWithIdentifier:@"userViewId"];
                            slider.MainVC = homet;
                            AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
                            UINavigationController *navigationVc = [[UINavigationController alloc]initWithRootViewController:slider];
                            navigationVc.navigationBar.hidden = YES;
                            delegate.window.rootViewController = navigationVc;
                        }
                            //    [self.navigationController pushViewController:slider animated:YES];
//                            [weakSelf.navigationController pushViewController:slider animated:YES];
                    }
                    else if ([retDic[@"c"] intValue] == 0)
                    {
                        [self performSegueWithIdentifier:@"landingToName" sender:nil];
                    }
                }
                else if ([retDic[@"a"] intValue] == 0)
                {
                    NSLog(@"00000000000");
                }
                else if([retDic[@"a"] intValue] == -1)
                {
                    NSLog(@"-11111111");
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"shibai ");
                _mbProgressHud.hidden = YES;
            }];
        }});
}

#pragma mark -
#pragma mark 导航返回按钮
- (IBAction)backClick {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)qqClick {
    [self.view endEditing:YES];//键盘回收
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToQQ];
    
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        //获取微博用户名、uid、token等
        if (response.responseCode == UMSResponseCodeSuccess) {
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToQQ];
            NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
            NSDictionary *dic= @{@"uid":snsAccount.usid};
            AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
            httpManager.requestSerializer = [[AFHTTPRequestSerializer alloc] init];
            httpManager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
            //地址
            [httpManager POST:URL_REGIST_ANOTHER parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
                UserConfig *config = [UserConfig sharingUserConfig];
                NSDictionary *retDic = [NetworkTool toNSDictionary:responseObject];
//                __weak LandingViewController *weakSelf = self;
                if ([retDic[@"a"] intValue] == 1) {
                    NSLog(@"111111111111");
                    [config setToken:retDic[@"b"]];
                    if ([retDic[@"c"] intValue] == 1)
                    {
                        BOOL HaveRoot = NO;//标记是否有Root
                        for (UIViewController * controller in self.navigationController.viewControllers)
                        {
                            if ([controller isKindOfClass:[SliderViewController class]])
                            {//如果是rootView
                                HaveRoot = YES;
                                [self.navigationController popToViewController:controller animated:YES];
                            }
                        }
                        if (!HaveRoot)
                        {
                            HomeTwoViewController *homet = [[HomeTwoViewController alloc] init];
                            SliderViewController *slider = [SliderViewController sharedSliderController];
                            [config setHaveLogin:@"login"];
                            
                            if (SCREEN_WIDTH > 320)
                            {
                                slider.LeftSContentOffset =  SCREEN_WIDTH-WIDTH_MAIN_6*SCREEN_SCALE;//SXW__设置侧边栏
                            }
                            else
                            {
                                slider.LeftSContentOffset =  SCREEN_WIDTH-WIDTH_MAIN*SCREEN_SCALE;//SXW__设置侧边栏
                            }
                            slider.LeftSContentScale = 1;//左视图缩小，1表示不缩小。
                            
                            UIStoryboard *userSt = [UIStoryboard storyboardWithName:@"User" bundle:nil];
                            slider.LeftVC = [userSt instantiateViewControllerWithIdentifier:@"userViewId"];
                            
                            slider.MainVC = homet;
                        
                        
                            AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
                            //TODO:ROOTVIEWCONTROLLER
                            UINavigationController *navigationVc = [[UINavigationController alloc]initWithRootViewController:slider];
                            navigationVc.navigationBar.hidden = YES;
                            delegate.window.rootViewController = navigationVc;
                        }
                            //    [self.navigationController pushViewController:slider animated:YES];
//                            [weakSelf.navigationController pushViewController:slider animated:YES];
                    
                    }else if ([retDic[@"c"] intValue] == 0)
                    {
                        [self performSegueWithIdentifier:@"landingToName" sender:nil];
                    }
                } else if ([retDic[@"a"] intValue] == 0) {
                    NSLog(@"00000000000");
                }else if([retDic[@"a"] intValue] == -1){
                    NSLog(@"-11111111");
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"shibai ");
                _mbProgressHud.hidden = YES;
            }];
        }});
}

@end
